package com.mamingchao.concurrent.four_thread_creation_way;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  这是通过implements Runable创建进程
 *
 * Created by mamingchao on 2020/9/22.
 *
 */
public class ImplementsCallable<T> implements Callable<T>{

    static ReentrantLock fairLock = new ReentrantLock(true);

    private String threadName;

    public ImplementsCallable(String threadName) {
        this.threadName = threadName;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Callable<String> threadImplCallable = new ImplementsCallable<String>("Thread1");
        FutureTask<String> futureTask = new FutureTask<>(threadImplCallable);
        Thread thread = new Thread(futureTask);
        thread.start();
        String rValue = futureTask.get();
        System.out.println("Thread1 return value is " + rValue);

        threadImplCallable = new ImplementsCallable<>("Thread2");
        futureTask = new FutureTask<>(threadImplCallable);
        thread = new Thread(futureTask);
        thread.start();
        rValue = futureTask.get();
        System.out.println("Thread2 return value is " + rValue);

        System.out.println("end");


    }

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public T call() throws Exception {

        for (int i = 0; i <26; i++) {
            fairLock.lock();
            System.out.println(threadName + "-" +i);
            fairLock.unlock();
        }
        return null;
    }
}
